package com.hmall.gateway.filter;

import com.hmall.common.exception.UnauthorizedException;
import com.hmall.common.utils.CollUtils;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.util.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@Slf4j
@Order(-1)
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthFilter implements GlobalFilter {

    private final JwtTool jwtTool;
    private final AuthProperties authProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取Request
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 获取当前请求的路径
        String path = request.getURI().getPath();

        // 获取配置中无需拦截的路径列表
        List<String> excludePaths = authProperties.getExcludePaths();

        // 检查当前请求路径是否匹配配置中的无需拦截路径
        for (String excludePath : excludePaths) {
            if (antPathMatcher.match(excludePath, path)) {
                log.info("无需拦截：{}", path);
                // 如果匹配到排除路径，则直接放行，不进行后续的拦截逻辑
                return chain.filter(exchange);
            }
        }

        // 从请求头中获取Authorization字段的值，即token列表
        List<String> tokens = request.getHeaders().get("Authorization");

        // 如果token列表为空，则表示请求未提供身份验证信息，返回401未授权状态
        if(CollectionUtils.isEmpty(tokens)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        // 取出第一个token进行验证
        String token = tokens.get(0);

        // 初始化用户ID为null，用于后续的身份验证
        Long userId = null;

        try {
            // 使用JWT工具解析token，获取用户ID
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            // 如果token解析失败，记录错误日志，并返回401未授权状态
            log.error("token无效", e);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        // 记录验证通过的用户ID日志，表示身份验证成功
        log.info("用户id：{}", userId);
        String userIdStr = userId.toString();
        ServerWebExchange ex = exchange.mutate()
                .request(b -> b.header("userId", userIdStr))
                .build();
        // 放行请求，继续执行下一个过滤器或最终的请求处理
        return chain.filter(ex);
    }

    private boolean isExclude(String antPath) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(pathPattern, antPath)){
                return true;
            }
        }
        return false;
    }
}